package cn.baage.campus.utils;

import cn.baage.campus.config.security.BaseUserDetail;
import cn.baage.campus.model.dto.LoginUser;
import cn.baage.campus.model.dto.UserRoleDTO;
import cn.baage.campus.model.po.Role;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Description: 安全认证工具
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
public class SecurityUtils {


    public static boolean isLogin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && !"anonymousUser".equals(authentication.getPrincipal());
    }


    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public static BaseUserDetail getLoginUserDetail() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return (BaseUserDetail) authentication.getPrincipal();
    }


    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public static LoginUser getLoginUser() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return ((BaseUserDetail) authentication.getPrincipal()).getLoginUser();
    }


    /**
     * 获取登录信息
     *
     * @param user 数据库信息
     * @return UserDetail
     */
    public static BaseUserDetail user2UserDetail(UserRoleDTO user) {
        BaseUserDetail baseUserDetail = new BaseUserDetail();
        LoginUser loginUser = BeanUtil.copyProperties(user, LoginUser.class);
        List<String> roles = new ArrayList<>();
        for (Role role : user.getRoles()) {
            roles.add(role.getKey());
        }
        loginUser.setRoles(roles);
        baseUserDetail.setLoginUser(loginUser);
        baseUserDetail.setPassword(user.getPassword());
        baseUserDetail.setEnable(!Optional.ofNullable(user.getDelFlag()).orElse(false));
        Integer status = Optional.ofNullable(user.getStatus()).orElse(1);
        baseUserDetail.setLock(!(status == 0));
        return baseUserDetail;
    }


}
